//
//  DetailViewController.m
//  CapriceMusic
//
//  Created by 蒋恩浩 on 16/1/7.
//  Copyright © 2016年 MYX. All rights reserved.
//

#import "DetailViewController.h"

@interface DetailViewController ()<UITableViewDelegate, UITableViewDataSource, synchroPlayAndPlayControl>

@property (nonatomic, strong) UISegmentedControl *segment;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *commentDataSource;
@property (nonatomic, strong) DetailModel *detailModel;
@property (nonatomic, strong) UIImageView *backPicture;
// 播放器
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerLayer *playerLayer;
@property (nonatomic, strong) AVPlayerItem *playerItem;
// 控制台
@property (nonatomic, strong) UIView *controlTable;
// 视频总时间
@property (nonatomic, assign) float videoTimes;
// 控制台上面视图（点击事件）
@property (nonatomic, strong) UIView *tapView;
// 播放暂停
@property (nonatomic, strong) UIButton *playControlButton;
// 进度条
@property (nonatomic, strong) UISlider *progressBar;
@property (nonatomic, strong) NSTimer *timer;
// 时间
@property (nonatomic, assign) NSInteger minutes;
@property (nonatomic, assign) NSInteger seconds;
@property (nonatomic, strong) JEHLabel *timesLabel;
// 全屏
@property (nonatomic, strong) UIButton *fullScreen;
// 视频菊花
@property (nonatomic, strong) UIActivityIndicatorView *indicator;
// 第一次全屏
@property (nonatomic, assign) NSInteger *isFirstToPlayerVC;

@end

// 播放暂停标记
static NSInteger playControlFlag = 1;
static NSString *idType = nil;
static NSString *netWorkUrl = nil;
static NSString *commentNetWorkUrl = nil;

@implementation DetailViewController

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - lifeCycle
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.tabBarController.tabBar.translucent = YES;
    self.tabBarController.tabBar.hidden = YES;
    // 关闭抽屉侧滑效果
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [tempAppDelegate.LeftSlideVC setPanEnabled:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isFirstToPlayerVC = 0;
    [self setUpNavigation];
    [self netWorkParameter];
    [self createSegment];
    [self createTableView];
    [self getDetailDataWithURL:netWorkUrl];
    [self tableOfVideoControl];
    self.commentDataSource = [NSMutableArray arrayWithCapacity:0];
    [self pullDownUpdate];
    [self pullUpLoading];
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(receiveNotification:) name:@"collect" object:nil];
}
#pragma mark - 通知
- (void)receiveNotification:(NSNotification *)messages {
    NSString *str = messages.object;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:str preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - 判断网络请求参数
- (void)netWorkParameter {
    
    if ([self.type isEqualToString:@"VIDEO"] || [self.type isEqualToString:@"FANART"] || [self.type isEqualToString:@"PROGRAM"]) {
        
        idType = @"videoId";
        netWorkUrl = kJieMuMvGETURL;
        commentNetWorkUrl = kJieMuMvCommentGETURL;
    } else {
        idType = @"id";
        netWorkUrl = kStarYueDanGETURL;
        commentNetWorkUrl = kStarYueDanCommentGETURL;
    }
}

#pragma mark - 设置导航栏
- (void)setUpNavigation {
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(backDidPress:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"whitePoint"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(rightBarButtonAction)];
}

#pragma mark - navigation按钮点击事件
- (void)backDidPress:(UIBarButtonItem *)sender {
    
    self.tabBarController.tabBar.hidden = NO;
    self.tabBarController.tabBar.translucent = NO;
    [self.player pause];
    [self.playerLayer removeFromSuperlayer];
    [self.timer invalidate];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"DeletePlayer" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightBarButtonAction {
    
    // 详情选项
    UIActionSheet *actionsheet = [[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"下载", @"收藏", nil];
    actionsheet.actionSheetStyle = UIActionSheetStyleAutomatic;
    [actionsheet showInView:self.view];
}
#pragma mark - 下载、收藏
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == 0) {
        
        DownLoadViewController *down = [DownLoadViewController shareDownLoadManager];
        [down downLoad:self.detailModel.url];
        DataBaseHandle *data = [DataBaseHandle shareDataBase];
        [data openDataBase];
        [data createDownloadingTable];
        [data insertDownloadingDatabase:self.detailModel.title withPicture:self.detailModel.posterPic withDownloadUrl:self.detailModel.url];
        [data closedDataBase];
    }else if (buttonIndex == 1) {
        
        NSString *typeString = [idType isEqualToString:@"id"] ? @"YueDan" : @"VIDEO";
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        BOOL mybool = YES;
        DataBaseHandle *dataBaseHandle = [DataBaseHandle shareDataBase];
        [dataBaseHandle openDataBase];
        [dataBaseHandle createTable];
        NSMutableArray *array = [dataBaseHandle selectDataBase];
        if (array.count == 0) {
            [dataBaseHandle insertDatabase:self.detailModel.title withids:self.detailModel.ids.stringValue withType:typeString withImageUrl:self.detailModel.albumImg];
            
            [center postNotificationName:@"collect" object:@"收藏成功" userInfo:nil];
        }else {
            for (NSDictionary *dic in array) {
                if ([[dic valueForKey:@"ids"] isEqualToString:self.detailModel.ids.stringValue]) {
                    [center postNotificationName:@"collect" object:@"亲,您已经收藏过了" userInfo:nil];
                    mybool = NO;
                    break;
                }
            }
            if (mybool) {
                [dataBaseHandle insertDatabase:self.detailModel.title withids:self.detailModel.ids.stringValue withType:typeString withImageUrl:self.detailModel.albumImg];
                [center postNotificationName:@"collect" object:@"收藏成功" userInfo:nil];
            }
            [dataBaseHandle closedDataBase];
        }
        
    }else if (buttonIndex == 2) {
        
        NSLog(@"分享");
    }
}

//http://mapi.yinyuetai.com/video/show.json?D-A=0&relatedVideos=true&id=2464560
//节目、mv页面
//#define kJieMuMvGETURL @"http://mapi.yinyuetai.com/video/show.json?D-A=0"
//悦单，star页面
//#define kStarYueDanGETURL @"http://mapi.yinyuetai.com/playlist/show.json?D-A=0"
#pragma mark - detail页网络请求(http://mapi.yinyuetai.com/video/show.json?D-A=0&relatedVideos=true&id=2442052)
- (void)getDetailDataWithURL:(NSString *)url {

    [JEHNetWorkTool getWithUrl:url parameter:@{@"relatedVideos":@"true", @"id":[NSString stringWithFormat:@"%d", self.appendingId.intValue]} httpHeader:@{@"App-Id":@"10201029",@"Device-Id":@"5fc617ae1220d0969b23eaab4c8f02b5",@"Device-V":@"QW5kcm9pZF80LjQuNF8xMDgwKjE5MjBfMTEwMDA5MDAw"} responseType:ResponseTypeJSON success:^(id result) {
        
        NSDictionary *dictionary = result;
        self.detailModel = [[DetailModel alloc] initWithDictionary:dictionary];
        dispatch_async(dispatch_get_main_queue(), ^{

            if ([idType isEqualToString:@"id"]) {
                
                [self createPlayerViewWithUrl:[self.detailModel.relatedVideosDataSource[0] url]];
                self.tableView.userInteractionEnabled = YES;
            } else {
                [self createPlayerViewWithUrl:self.detailModel.url];
            }
            [self.indicator stopAnimating];
            [self.tableView reloadData];
        });
    } fail:^(NSError *error) {
        
        
    }];
}

//节目、mv页面评论
//#define kJieMuMvCommentGETURL @"http://mapi.yinyuetai.com/video/comment/list.json?D-A=0"
//悦单，star页面评论
//#define kStarYueDanCommentGETURL @"http://mapi.yinyuetai.com/playlist/comment/list.json?D-A=0"
static NSInteger number = 0;
#pragma mark - 评论网络请求
- (void)getCommentDataWithIdType:(NSString *)idType withURL:(NSString *)url {

    NSString *offsetNum = [NSString stringWithFormat:@"%ld", number];
    [JEHNetWorkTool getWithUrl:url parameter:@{@"v":@"2", idType:[NSString stringWithFormat:@"%d", self.appendingId.intValue], @"size":@"10", @"offset":offsetNum} httpHeader:@{@"App-Id":@"10201029",@"Device-Id":@"5fc617ae1220d0969b23eaab4c8f02b5",@"Device-V":@"QW5kcm9pZF80LjQuNF8xMDgwKjE5MjBfMTEwMDA5MDAw"} responseType:ResponseTypeJSON success:^(id result) {

        NSArray *array = result[@"comments"];
        for (NSDictionary *dictionary in array) {
            
            DetailCommentModel *comment = [[DetailCommentModel alloc] initWithDictionary:dictionary];
            [self.commentDataSource addObject:comment];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.tableView reloadData];
        });
    } fail:^(NSError *error) {
        
    }];
}

#pragma mark - 创建segment
- (void)createSegment {

    if ([idType isEqualToString:@"videoId"]) {
        
        self.segment = [[UISegmentedControl alloc] initWithItems:@[@"MV描述", @"评论", @"相关MV"]];
        self.segment.selectedSegmentIndex = 0;
    } else {
        self.segment = [[UISegmentedControl alloc] initWithItems:@[@"悦单描述", @"悦单评论", @"悦单列表"]];
        self.segment.selectedSegmentIndex = 2;
    }
    self.segment.frame = CGRectMake(20, self.view.width * 230 / 414 + 40, self.view.width - 40, 30);
    self.segment.tintColor = [UIColor colorWithRed:30 / 255.0 green:195 / 255.0 blue:153 / 255.0 alpha:1.0];
    [self.segment addTarget:self action:@selector(segmentEvent:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.segment];
}

#pragma mark - segment事件
- (void)segmentEvent:(UISegmentedControl *)segmentControl {
    
    if (segmentControl.selectedSegmentIndex == 0) {
        
        self.tableView.bounces = NO;
        [self.tableView reloadData];
    } else if (segmentControl.selectedSegmentIndex == 1) {
        
        self.tableView.bounces = YES;
        [self.tableView reloadData];
        [self getCommentDataWithIdType:idType withURL:commentNetWorkUrl];
    } else {
        self.tableView.bounces = NO;
        [self.tableView reloadData];
    }
}

#pragma mark - 创建tableView
- (void)createTableView {
    
    // 背景图片
    self.backPicture = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.view.width * 230 / 414 + 30 + 50, self.view.width, self.view.height - 64 - self.view.width * 230 / 414 - 50 - 30)];
    [self.view addSubview:self.backPicture];
    // 毛玻璃效果
    UIVisualEffectView *visualView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]];
    visualView.frame = CGRectMake(0, self.view.width * 230 / 414 + 30 + 50, self.view.width, self.view.height - 64 - self.view.width * 230 / 414 - 50 - 30);
    [self.view addSubview:visualView];
    // 创建tableView
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.view.width * 230 / 414 + 30 + 50, self.view.width, self.view.height - 64 - self.view.width * 230 / 414 - 50 - 30) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.bounces = NO;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.tableView registerClass:[DetailTableViewCell class] forCellReuseIdentifier:@"DetailTableViewCell"];
    [self.tableView registerClass:[CommentTableViewCell class] forCellReuseIdentifier:@"CommentTableViewCell"];
    [self.tableView registerClass:[RelatedVideosTableViewCell class] forCellReuseIdentifier:@"RelatedVideosTableViewCell"];
    [self.tableView registerClass:[SecondDetailTableViewCell class] forCellReuseIdentifier:@"SecondDetailTableViewCell"];
    [self.tableView registerClass:[YueDanDetailTableViewCell class] forCellReuseIdentifier:@"YueDanDetailTableViewCell"];
    [self.view addSubview:self.tableView];
}

#pragma mark - tableViewDelegateMethod
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (_detailModel) {
        
        if (self.segment.selectedSegmentIndex == 0) {
            
            if ([idType isEqualToString:@"videoId"]) {
                
                return self.detailModel.artistsDataSource.count + 1;
            } else {
                return 1;
            }
        } else if (self.segment.selectedSegmentIndex == 1 && self.commentDataSource.count > 0) {

            return self.commentDataSource.count;
        } else if (self.segment.selectedSegmentIndex == 2) {
            
            return self.detailModel.relatedVideosDataSource.count;
        }
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.segment.selectedSegmentIndex == 0) {
        
        if ([idType isEqualToString:@"id"]) {
            
            YueDanDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YueDanDetailTableViewCell"];
            cell.detailModel = self.detailModel;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        } else {
            if (indexPath.row == self.detailModel.artistsDataSource.count) {
                
                SecondDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SecondDetailTableViewCell"];
                cell.detailModel = self.detailModel;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
            } else {
                DetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DetailTableViewCell"];
                DetailDescriptionModel *description = self.detailModel.artistsDataSource[indexPath.row];
                cell.detailDescriptionModel = description;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
            }
        }
    } else if (self.segment.selectedSegmentIndex == 1 && self.commentDataSource.count > 0) {
        
        CommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommentTableViewCell"];
        cell.detailCommentModel = self.commentDataSource[indexPath.row];
        if (cell.detailCommentModel.hot.intValue == 1) {
            
            cell.hotLabel.alpha = 1;
        } else {
            cell.hotLabel.alpha = 0;
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else {
        RelatedVideosTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RelatedVideosTableViewCell"];
        cell.relatedVideoModel = self.detailModel.relatedVideosDataSource[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if ([idType isEqualToString:@"videoId"]) {
            
            cell.idType = @"VIDEO";
        } else {
            cell.idType = @"YueDan";
        }
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_detailModel) {
        
        if (self.segment.selectedSegmentIndex == 0) {

            if ([idType isEqualToString:@"videoId"] && indexPath.row == self.detailModel.artistsDataSource.count) {
                
                return [AdaptCellHeight getHeightwithFont:14 withText:self.detailModel.descriptions withWidth:self.view.width - 40] + 40 + 14;
            } else if ([idType isEqualToString:@"id"] && indexPath.row == self.detailModel.artistsDataSource.count) {
                
                return [AdaptCellHeight getHeightwithFont:14 withText:self.detailModel.descriptions withWidth:self.view.width - 40] + 80 + 14;
            } else {
                return 80;
            }
        } else if (self.segment.selectedSegmentIndex == 1 && self.commentDataSource.count > 0) {
            
            DetailCommentModel *detailComment = self.commentDataSource[indexPath.row];
            return [AdaptCellHeight getHeightwithFont:16 withText:detailComment.content withWidth:self.view.width - 40] + 140;
        } else {
            return 110;
        }
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return CGFLOAT_MIN;
}

#pragma mark - tableView点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (self.segment.selectedSegmentIndex == 0) {
        
        
    } else if (self.segment.selectedSegmentIndex == 2) {
        
        if ([idType isEqualToString:@"id"]) {
            
            RelatedVideosModel *relatedVideos = self.detailModel.relatedVideosDataSource[indexPath.row];
            [self.playerLayer removeFromSuperlayer];
            [self.player pause];
            [self.indicator startAnimating];
            [self createPlayerViewWithUrl:relatedVideos.url];
        } else {
            self.navigationItem.title = [self.detailModel.relatedVideosDataSource[indexPath.row] title];
            self.appendingId = [self.detailModel.relatedVideosDataSource[indexPath.row] ids];
            [self.playerLayer removeFromSuperlayer];
            [self.player pause];
            [self.indicator startAnimating];
            [self getDetailDataWithURL:netWorkUrl];
            self.tableView.userInteractionEnabled = NO;
        }
    }
}

#pragma mark - 创建播放器视图
- (void)createPlayerViewWithUrl:(NSString *)urlString {

    // 背景图片
    [self.backPicture sd_setImageWithURL:[NSURL URLWithString:self.detailModel.albumImg]];
    // 导航栏title
    self.navigationItem.title = self.detailModel.title;
    // 创建播放器视图
    NSURL *url = [NSURL URLWithString:urlString];
    AVAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
    self.playerItem = [AVPlayerItem playerItemWithAsset:asset];
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playerLayer.frame = CGRectMake(0, 0, self.view.width, self.view.width * 230 / 414);
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    [self.view.layer addSublayer:self.playerLayer];
    // 获取视频长度
    NSDictionary *movieLenght = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:movieLenght];
    self.videoTimes = urlAsset.duration.value / urlAsset.duration.timescale;
    // 进度条最大值
    self.progressBar.maximumValue = self.videoTimes;
    // 设置播放按钮图片
    [self.playControlButton setImage:[[UIImage imageNamed:@"stop"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    
    [self.timer setFireDate:[NSDate distantPast]];
    [self.player play];
}

#pragma mark - 进度条
- (void)timerAction {
    
    // 获取进度条位置，转换为时间
    self.progressBar.value = CMTimeGetSeconds(self.player.currentItem.currentTime) / CMTimeGetSeconds(self.player.currentItem.duration) * self.videoTimes;
    NSInteger currentMinute = self.progressBar.value / 60;
    NSInteger currentSecond = self.progressBar.value - currentMinute * 60;
    self.minutes = self.videoTimes / 60;
    self.seconds = self.videoTimes - self.minutes * 60;
    // 显示时间（当前时间/总时间）
    self.timesLabel.text = [NSString stringWithFormat:@"%02ld:%02ld/%02ld:%02ld", currentMinute, currentSecond, self.minutes, self.seconds];
    // 播放结束
    if (self.progressBar.value == self.progressBar.maximumValue) {
        
        [self playControlButtonAction];
    }
}

#pragma mark - 视频控制台
- (void)tableOfVideoControl {
    
    // 添加播放控制台点击手势及其视图
    self.tapView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.width * 230 / 414)];
    [self.view addSubview:self.tapView];
    // 单击控制播放
    UITapGestureRecognizer *playControlTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(playControlTapAction)];
    [self.tapView addGestureRecognizer:playControlTap];
    // 双击全屏手势
    UITapGestureRecognizer *allScreenTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(allScreenTap)];
    allScreenTap.numberOfTapsRequired = 2;
    [playControlTap requireGestureRecognizerToFail:allScreenTap];
    [self.tapView addGestureRecognizer:allScreenTap];
    // 添加菊花
     self.indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    self.indicator.center = self.tapView.center;
    [self.indicator startAnimating];
    [self.tapView addSubview:self.indicator];
    // 添加控制台
    self.controlTable = [[UIView alloc] initWithFrame:CGRectMake(0, self.tapView.height, self.view.width, 30)];
    self.controlTable.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.controlTable];
    // 播放控制按钮
    self.playControlButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.playControlButton.frame = CGRectMake(10, 0, 30, 30);
    [self.playControlButton addTarget:self action:@selector(playControlButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.controlTable addSubview:self.playControlButton];
    // 进度条
    self.progressBar = [[UISlider alloc] initWithFrame:CGRectMake(50, 0, self.controlTable.width - 130 - 50, 30)];
    self.progressBar.minimumValue = 0.0f;
    self.progressBar.minimumTrackTintColor = [UIColor colorWithRed:30 / 255.0 green:195 / 255.0 blue:153 / 255.0 alpha:1.0];
    [self.progressBar setThumbImage:[UIImage imageNamed:@"thumb"] forState:UIControlStateNormal];
    [self.progressBar addTarget:self action:@selector(thumbBeginScroll:) forControlEvents:UIControlEventTouchDown];
    [self.progressBar addTarget:self action:@selector(thumbBeingScroll:) forControlEvents:UIControlEventValueChanged];
    [self.progressBar addTarget:self action:@selector(thumbEndScroll:) forControlEvents:UIControlEventTouchUpInside];
    [self.controlTable addSubview:self.progressBar];
    // 进度条点击手势
    UITapGestureRecognizer *sliderTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sliderTapAction:)];
    [self.progressBar addGestureRecognizer:sliderTap];
    // 进度条timer
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    [self.timer setFireDate:[NSDate distantFuture]];
    // 时间label
    self.timesLabel = [[JEHLabel alloc] initWithFrame:CGRectMake(self.controlTable.width - 120, 0, 80, 30) withFont:13 withTextColor:[UIColor whiteColor]];
    [self.controlTable addSubview:self.timesLabel];
    // 全屏按钮
    self.fullScreen = [UIButton buttonWithType:UIButtonTypeCustom];
    self.fullScreen.frame = CGRectMake(self.view.width - 40, 0, 30, 30);
    [self.fullScreen setImage:[UIImage imageNamed:@"fullScreen"] forState:UIControlStateNormal];
    [self.fullScreen addTarget:self action:@selector(allScreenButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.controlTable addSubview:self.fullScreen];
}

#pragma mark - 双击全屏手势
- (void)allScreenTap {
    
    [self allScreenButtonAction];
}

#pragma mark - 控制台播放控制点击手势事件
- (void)playControlTapAction {
    
    [self playControlButtonAction];
}

#pragma mark - 播放控制按钮点击事件
- (void)playControlButtonAction {
    
    if (self.progressBar.value == self.progressBar.maximumValue) {
        
        self.timesLabel.text = [NSString stringWithFormat:@"00:00/%02ld:%02ld", self.minutes, self.seconds];
        CMTime playFromTime = CMTimeMake(0, 1);
        [self.player seekToTime:playFromTime];
    }
    if (playControlFlag == 1) {
        
        [self.player pause];
        [self.timer setFireDate:[NSDate distantFuture]];
        [self.playControlButton setImage:[UIImage imageNamed:@"start"] forState:UIControlStateNormal];
        playControlFlag = 0;
    } else {
        [self.player play];
        [self.timer setFireDate:[NSDate distantPast]];
        [self.playControlButton setImage:[UIImage imageNamed:@"stop"] forState:UIControlStateNormal];
        playControlFlag = 1;
    }
}

#pragma mark - 滑块拖动事件
- (void)thumbBeginScroll:(UISlider *)slider {
    
    [self.player pause];
    // 计时器暂停
    [self.timer setFireDate:[NSDate distantFuture]];
}

- (void)thumbBeingScroll:(UISlider *)slider {
    
    NSInteger minutes = slider.value / 60;
    NSInteger seconds = slider.value - minutes * 60;
    self.timesLabel.text = [NSString stringWithFormat:@"%02ld:%02ld/%02ld:%02ld", minutes, seconds, self.minutes, self.seconds];
}

- (void)thumbEndScroll:(UISlider *)slider {
    
    CMTime playFromTime = CMTimeMake(slider.value, 1);
    [self.player seekToTime:playFromTime completionHandler:^(BOOL finished) {
        
        [self.timer setFireDate:[NSDate distantPast]];
        [self.player play];
    }];
}

#pragma mark - 进度条点击手势
- (void)sliderTapAction:(UITapGestureRecognizer *)sliderTap {
    
    // 设置当前播放位置
    CGPoint point = [sliderTap locationInView:self.progressBar];
    self.progressBar.value = point.x * ((float)self.videoTimes / (float)(self.controlTable.width - 180));
    CMTime playFromTime = CMTimeMake(self.progressBar.value, 1);
    [self.player seekToTime:playFromTime];
    // 设置当前播放时间
    NSInteger minutes = self.progressBar.value / 60;
    NSInteger seconds = self.progressBar.value - minutes * 60;
    self.timesLabel.text = [NSString stringWithFormat:@"%02ld:%02ld/%02ld:%02ld",minutes, seconds, self.minutes, self.seconds];
    [self.timer setFireDate:[NSDate distantPast]];
    [self.player play];
}

#pragma mark - 全屏按钮
- (void)allScreenButtonAction {

    [self.player pause];
    [self.timer setFireDate:[NSDate distantFuture]];
    CustomPlayerViewController *customPlayerVC = [CustomPlayerViewController shareSinglePlayerViewController];
    if ([idType isEqualToString:@"id"]) {
        
        customPlayerVC.urlString = [self.detailModel.relatedVideosDataSource[0] url];
    } else {
        customPlayerVC.urlString = self.detailModel.url;
    }
    customPlayerVC.title = self.navigationItem.title;
    customPlayerVC.videoTimes = self.videoTimes;
    customPlayerVC.playControlFlag = playControlFlag;
    customPlayerVC.currentValue = self.progressBar.value;
    customPlayerVC.delegate = self;
    customPlayerVC.isLocal = NO;
    
    NSUserDefaults *firstAllScreen = [NSUserDefaults standardUserDefaults];
    if ([firstAllScreen objectForKey:@"First"] == nil) {
        
        [firstAllScreen setObject:@"YES" forKey:@"First"];
    } else {
        [customPlayerVC createPlayerView];
    }
#warning 加动画，播放器会闪退
    // 添加动画
//    customPlayerVC.modalTransitionStyle = UIModalTransitionStylePartialCurl;
    [self presentViewController:customPlayerVC animated:YES completion:^{
        
    }];
}

#pragma mark - 同步协议方法
- (void)progressBarValue:(float)currentValue withIsPlay:(NSInteger)flag {
    
    self.progressBar.value = currentValue;
    playControlFlag = flag;
    CMTime playFromTime = CMTimeMake(self.progressBar.value, 1);
    [self.player seekToTime:playFromTime];
    NSInteger minutes = self.progressBar.value / 60;
    NSInteger seconds = self.progressBar.value - minutes * 60;
    self.timesLabel.text = [NSString stringWithFormat:@"%02ld:%02ld/%02ld:%02ld", minutes, seconds, self.minutes, self.seconds];

    if (playControlFlag == 1) {
        
        [self.player play];
        [self.timer setFireDate:[NSDate distantPast]];
        [self.playControlButton setImage:[UIImage imageNamed:@"stop"] forState:UIControlStateNormal];
    } else {
        [self.player pause];
        [self.timer setFireDate:[NSDate distantFuture]];
        [self.playControlButton setImage:[UIImage imageNamed:@"start"] forState:UIControlStateNormal];
    }
}

#pragma mark -- 上拉加载
-(void)pullUpLoading {
    
    __weak typeof(self) weakSelf = self;
    [self.tableView addFooterWithCallback:^{
        
        number += 10;
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 *NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [weakSelf getCommentDataWithIdType:idType withURL:commentNetWorkUrl];
        [weakSelf.tableView footerEndRefreshing];
//        });
    }];
}

#pragma mark -- 下拉刷新
-(void)pullDownUpdate {
    
    __weak typeof(self) weakSelf = self;
    [self.tableView addHeaderWithCallback:^{
        
        number = 0;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 *NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [weakSelf.commentDataSource removeAllObjects];
        [weakSelf getCommentDataWithIdType:idType withURL:commentNetWorkUrl];
        [weakSelf.tableView headerEndRefreshing];
        });
    }];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
